package com.hongkuncheng.cms.controller.admin;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.sql.JoinType;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.helper.DataHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.helper.StringHelper;
import com.hongkuncheng.cms.model.Admin;
import com.hongkuncheng.cms.model.Article;
import com.hongkuncheng.cms.model.ArticleState;
import com.hongkuncheng.cms.controller.BaseController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 文档管理
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/articlerecycled")
public class AarticlerecycledController extends BaseController {

    // 文档回收站列表
    @RequestMapping
    public String index() {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        Criteria criteriaArticle = factorySession.createCriteria(Article.class, "this_")
                .createAlias("admin", "article_admin", JoinType.LEFT_OUTER_JOIN)
                .createAlias("article_admin.department", "article_admin_department", JoinType.LEFT_OUTER_JOIN);
        StringBuilder callbackparams = new StringBuilder();
        boolean onlyme = request.getParameter("onlyme") != null;
        request.setAttribute("onlyme", onlyme);
        if (onlyme || admin.getAdminGlobalpermission().getId() == 1) {
            criteriaArticle.add(Restrictions.eq("article_admin.id", admin.getId()));
            callbackparams.append("&onlyme=1");
        } else if (admin.getAdminGlobalpermission().getId() == 2) {
            criteriaArticle.add(Restrictions.eq("article_admin_department.id", admin.getDepartment().getId()));
        }
        String title = request.getParameter("title") == null ? "" : request.getParameter("title");
        if (!title.isEmpty()) {
            criteriaArticle.add(Restrictions.like("title", title, MatchMode.ANYWHERE));
            callbackparams.append("&title=" + title);
        }
        request.setAttribute("title", title);
        criteriaArticle.add(Restrictions.eq("articleState.id", 5));
        if (callbackparams.length() > 0) callbackparams.deleteCharAt(0);
        request.setAttribute("callbackparams", callbackparams);
        int pageIndex = request.getParameter("pageindex") == null || request.getParameter("callbackparams") != null &&
                !callbackparams.toString().equals(request.getParameter("callbackparams")) ? 1 :
                Integer.parseInt(request.getParameter("pageindex"));
        int datasize = getDataSize();
        List<Article> articles = criteriaArticle.addOrder(Order.desc("removetime"))
                .setFirstResult((pageIndex - 1) * datasize).setMaxResults(datasize).list();
        request.setAttribute("articles", articles);
        request.setAttribute("pageindex", pageIndex);
        int recordcount = articles.size() == 0 ? 0 : Integer.parseInt(criteriaArticle.setProjection(Projections.count("id")).setProjection(Projections.countDistinct("id")).setFirstResult(0).uniqueResult().toString());
        request.setAttribute("recordcount", recordcount);
        int pagecount = DataHelper.calcPageCount(recordcount, datasize);
        request.setAttribute("pagecount", pagecount);
        return view();
    }

    // 文档恢复
    @RequestMapping("recover")
    @ResponseBody
    public void recover() {
        checkAdminPermission("office_article_recycled");
        String[] articleIds = request.getParameter("articleids").split(",");
        List<Article> articles = factorySession.createCriteria(Article.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(articleIds)))
                .setLockMode(LockMode.PESSIMISTIC_WRITE).list();
        for (Article article : articles) {
            article.setArticleState(factorySession.load(ArticleState.class, 1));
            article.setRemovetime(null);
        }
        recordLog("恢复《" + articles.get(0).getTitle().trim() + "...》等" + articles.size() + "篇文档");
        PageHelper.alertAndRedirect("恢复成功", "./?" + request.getParameter("callbackparams"));
    }

    // 永久删除
    @RequestMapping("delete")
    @ResponseBody
    public void delete() {
        checkAdminPermission("office_article_recycled");
        String[] articleIds = request.getParameter("articleids").split(",");
        List<Article> articles = factorySession.createCriteria(Article.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(articleIds)))
                .setLockMode(LockMode.PESSIMISTIC_WRITE).list();
        for (Article article : articles) factorySession.delete(article);
        recordLog("删除《" + articles.get(0).getTitle().trim() + "...》等" + articles.size() + "篇文档");
        PageHelper.alertAndRedirect("删除成功", "./?" + request.getParameter("callbackparams"));
    }

}
